import type { AxiosProgressEvent } from 'axios'

export interface UploadEntity {
  onProgress: Function
  file: File
  filename: string
  publicAccess?: boolean // 是否上传到公有OSS
}
export interface UploadProgressEvent extends AxiosProgressEvent {
  percent: number
}
export interface OSSTokenEntity {
  stsToken: string
  accessKeySecret: string
  accessKeyId: string
  region: string
  bucket: string
  expiration: string
}
export const apiCommon = {
  upload: (data: UploadEntity): Promise<any> => {
    const { onProgress, file } = data
    return api.upload({
      url: 'demand/oss/files',
      onUploadProgress(e) {
        const progress = { ...e } as UploadProgressEvent
        if (e.total && e.total > 0) {
          progress.percent = (e.loaded / e.total) * 100
        }
        onProgress(progress)
      },
      data: {
        file,
      },
    })
  },
  ossToken: (): Promise<OSSTokenEntity> => {
    return api.query({
      url: 'file/token',
    })
  },
}
